package com.codebase.zookeeper.zkClient;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.junit.Test;

import java.util.List;

/**
 * @describe: zkClient 的增删改查和是事件订阅
 */
public class ZkClientTest {

    /**
     * 连接
     */
    @Test
    public void connectTest(){
        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
        System.out.println("连接成功");
    }

    /**
     * 创建节点
     */
    @Test
    public void createNodeTest(){
        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
        zkClient.createPersistent("/root/node1",true);
    }

    /**
     * 删除节点
     */
    @Test
    public void deleteTest(){
        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
        zkClient.delete("/root/node1", -1);
    }

    /***
     * 获取节点下的子节点
     */
    @Test
    public void getChildrenTest(){
        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
        List<String> stringList = zkClient.getChildren("/root");
        System.out.println(stringList);
    }

    /**
     * 设置数据
     */
    @Test
    public void writeData(){
        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
        zkClient.writeData("/root", "111");
    }

    /**
     * 获取节点的数据
     */
    @Test
    public void getData(){
        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
        String data = zkClient.readData("/root/node1", true);
        System.out.println(data);
    }

    /**
     * 订阅通知
     */
    @Test
    public void subscribeNotice() throws InterruptedException{
        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
        zkClient.createEphemeral("/ep_root", "aa");
        zkClient.subscribeDataChanges("/ep_root", new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {
                System.out.println("数据改变");
            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println("数据被删除");
            }
        });


        zkClient.subscribeChildChanges("/ep_root", new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                System.out.println("子节点被修改");
            }
        });

        zkClient.writeData("/ep_root", "111");

        Thread.sleep(1000);

    }

}
